package com.ptu.controller.user;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.ptu.dto.UserDTO;
import com.ptu.dto.UserLoginDTO;
import com.ptu.server.OSSService;
import com.ptu.server.UserServer;
import com.ptu.util.CodeWebSocketHandler;
import com.ptu.util.Result;
import com.ptu.util.UserHolder;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@RestController("userUserController")
@Slf4j
@Tag(name = "用户模块")
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserServer  userServer;
    @Autowired
    private CodeWebSocketHandler codeWebSocketHandler;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private OSSService ossService;

    //注册
    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public Result<Void> register(@RequestBody UserDTO userDTO) {
        System.out.println("用户注册" + userDTO);
        userServer.register(userDTO);
        return Result.success();
    }
    /**
     * 发送手机验证码
     */
    @Operation(summary = "发送手机验证码")
    @PostMapping("code")
    public Result sendCode(@RequestBody Map<String, String> requestBody, HttpSession session) {
        String phone = requestBody.get("phone");
        return userServer.sendCode(phone, session);
    }

    /**
     * 登录功能
     * @param loginForm 登录参数，包含手机号、验证码，图形验证码
     */
    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public Result login(@RequestBody UserLoginDTO loginForm, HttpSession session){
        return userServer.login(loginForm, session);
    }

    //获取用户信息
    @Operation(summary = "获取用户信息")
    @GetMapping("/info")
    public Result<UserDTO> info() {
        UserDTO user = userServer.getUser();
        return Result.success(user);
    }

    @Operation(summary = "退出登录")
    @PostMapping("/logout")
    public Result<Void> logout(HttpSession session) {
        //从UserH获取电话号码
        String phone = UserHolder.getUser().getPhone();
        stringRedisTemplate.delete("login:token:" + phone);
        System.out.println("退出登录,删除redis数据");
        UserHolder.removeUser();
        System.out.println("退出登录,删除UserHolder数据");
        return Result.success();
    }

    @Operation(summary = "修改个人信息")
    @PostMapping("/update")
    public Result<Void> update(@RequestBody UserDTO userDTO) {
        userServer.update(userDTO);
        return Result.success();
    }

    @Operation(summary = "上传用户头像")
    @PostMapping("/upload/avatar")
    public Result<String> uploadAvatar(@RequestParam("file") MultipartFile file) {
        System.out.println("上传用户头像");
        try {
            // 验证文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return Result.error("请上传图片文件");
            }

            // 验证文件大小（2MB）
            if (file.getSize() > 2 * 1024 * 1024) {
                return Result.error("图片大小不能超过2MB");
            }

            // 获取用户当前头像URL
            UserDTO currentUser = UserHolder.getUser();
            String oldAvatarUrl = currentUser != null ? currentUser.getImg() : null;

            // 上传到OSS，同时删除旧头像
            String imageUrl = ossService.uploadFile(file, oldAvatarUrl);

            // 更新用户头像
            UserDTO userDTO = new UserDTO();
            userDTO.setId(currentUser.getId());
            userDTO.setImg(imageUrl);
            userServer.update(userDTO);

            return Result.success(imageUrl);
        } catch (IOException e) {
            System.out.println("上传失败" + e);
            return Result.error("上传失败");
        }
    }

    @Operation(summary = "保存用户头像URL")
    @PostMapping("/save/avatar")
    public Result<Void> saveAvatar(Integer id, String img) {
        System.out.println("保存用户头像" + id + " " + img);
        userServer.saveAvatar(id, img);
        return Result.success();
    }


    @Operation(summary = "注册上传头像")
    @PostMapping("/upload/avatar/register")
    public Result<String> uploadAvatarRegister(@RequestParam("file") MultipartFile file) {
        System.out.println("注册上传头像");
        try {
            // 验证文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return Result.error("请上传图片文件");
            }

            // 验证文件大小（2MB）
            if (file.getSize() > 2 * 1024 * 1024) {
                return Result.error("图片大小不能超过2MB");
            }

            // 获取用户当前头像URL
            UserDTO currentUser = UserHolder.getUser();
            String oldAvatarUrl = currentUser != null ? currentUser.getImg() : null;

            // 上传到OSS，同时删除旧头像
            String imageUrl = ossService.uploadFile(file, oldAvatarUrl);

            return Result.success(imageUrl);
        } catch (IOException e) {
            System.out.println("上传失败" + e);
            return Result.error("上传失败");
        }
    }


    @Operation(summary = "获取图形验证码")
    @GetMapping("/captcha")
    public void captcha(HttpServletResponse response, HttpSession session) throws IOException {
        try {
            System.out.println("获取图形验证码");

            // 先设置响应头
            response.setContentType("image/jpeg");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);

            // 创建验证码
            LineCaptcha captcha = CaptchaUtil.createLineCaptcha(100, 40, 4, 40);
            String captchaCode = captcha.getCode();

            // 将验证码存入session
            session.setAttribute("captcha", captchaCode);
            System.out.println("验证码：" + captchaCode);

            // 输出图片
            captcha.write(response.getOutputStream());
            response.getOutputStream().flush();
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } finally {
            try {
                response.getOutputStream().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

//    @Operation(summary = "获取图形验证码")
//    @GetMapping("/captcha")
//    public void captcha(HttpServletResponse response, HttpSession session) throws IOException {
//
//
////        System.out.println("获取图形验证码");
////        // 创一个线性验证码实例
////        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(100,40,4,40);
////
////        // 获取验证码文本内容
////        String captchaCode = captcha.getCode();
////
////        // 将验证码存入session
////        session.setAttribute("captcha", captchaCode);
////        System.out.println("验证码：" + captchaCode);
////        // 输出图片到浏览器
////        captcha.write(response.getOutputStream());
////
////        // 可选：设置响应头防止缓存
////        response.setHeader("Pragma", "No-cache");
////        response.setHeader("Cache-Control", "no-cache");
////        response.setDateHeader("Expires", 0);
////        response.setContentType("image/jpeg");
//
//    }




}
